// 深度优先遍历
var numIslands = function (grid) {
  let res = 0;
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[0].length; j++) {
      if (grid[i][j] === "1") {
        res++;
        dfs(grid, i, j);
      }
    }
  }
  return res;
};

function dfs(grid, i, j) {
  // i j 越过矩阵边界
  // grid[i][j] == 0 代表此分支已经越过岛屿边界
  if (
    i < 0 ||
    j < 0 ||
    i > grid.length - 1 ||
    j > grid[0].length - 1 ||
    grid[i][j] == "0"
  )
    return;
  grid[i][j] = "0";
  dfs(grid, i + 1, j);
  dfs(grid, i - 1, j);
  dfs(grid, i, j + 1);
  dfs(grid, i, j - 1);
}
